﻿using System;
using System.Web;
using Actya.Core;

namespace Actya.Web.Infrastructure
{
	public class CmsToolbarHttpModule : IHttpModule
	{
		public void Init(HttpApplication context)
		{
			context.PostReleaseRequestState += context_PostReleaseRequestState;
		}

		void context_PostReleaseRequestState(object sender, EventArgs e)
		{
			// Render toolbar HTML and a link to toolbar css when the current user is logged-in and a member of the 
			// CmsAdministrators role.
			var app = sender as HttpApplication;
			if (app != null)
			{
				var context = new HttpContextWrapper(app.Context);

				if (context.Response.ContentType == "text/html" 
					&& ! context.Request.Path.ToLowerInvariant().Contains("cmsadmin")
					&& app.User != null
					&& app.User.Identity.IsAuthenticated 
					&& app.User.IsInRole(RoleNames.CmsAdministrators))
				{
					context.Response.Filter = new CmsToolbarFilter(context.Response.Filter, context); 
				}
			}
		}

		public void Dispose()
		{}
	}
}